package com.shuo.juc.latch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * CountDownLatch的唯一的field是sync, sync作为一个代理继承于AQS
 */
public class CountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(2);
        ExecutorService executor = Executors.newFixedThreadPool(5);
        executor.submit(()-> {
            System.out.println(Thread.currentThread().getName());
            sleeping(100);
            latch.countDown();
        });
        executor.submit(()-> {
            System.out.println(Thread.currentThread().getName());
            sleeping(2);
            latch.countDown();
        });
        // 阻塞, 2s后解除
        latch.await();
        System.out.println("ok");
        executor.shutdown();
    }

    private static void sleeping(int sec) {
        try {
            Thread.sleep(sec * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
